import * as API from "@/services";
import {deleteUserAuth, resetAuthPwd} from '@/services/system/auth/AuthService';
import {queryCurrentUser, queryUser} from '@/services/system/user/UserService';
import {ProList} from '@ant-design/pro-components';
import {Button, message, Tag} from 'antd';
import {KfModal, ModifyFormProps} from "kf-web-library";
import lodash from 'lodash';
import React, {ReactElement, useEffect, useState} from 'react';
import './AuthList.less';
import CreateAuthForm from './CreateAuthForm';
import ModifyPasswordForm from './ModifyPasswordForm';

export interface AuthInfoProps extends Partial<ModifyFormProps> {
}

const AuthList: React.FC<AuthInfoProps> = (props) => {
  const [loading, setLoading] = useState(false);
  const [bizData, setBizData] = useState<API.User>();

  const [modifyPwdModalVisiable, setModifyPwdModalVisiable] = useState(false);
  const [modifyPwdAuth, setModifyPwdAuth] = useState<API.Auth | null>(null);

  const [createAuthModalVisiable, setCreateAuthModalVisiable] = useState(false);

  const loadData = () => {
    setLoading(true);
    let processPromise;
    if (props.bizId) {
      processPromise = queryUser(props.bizId);
    } else {
      processPromise = queryCurrentUser();
    }
    processPromise
      .then((res) => {
        if (res.flag) {
          setBizData(res.data);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    loadData();
  }, []);

  const getIdentityTypeDesc = (identityType: string) => {
    let desc: ReactElement = <Tag color="blue">{identityType}</Tag>;
    switch (identityType) {
      case 'PWD_LOGIN_NAME':
        desc = <Tag color="blue">用户名类型</Tag>;
        break;
      case 'PWD_EMAIL':
        desc = <Tag color="geekblue">邮箱类型</Tag>;
        break;
      case 'PWD_MOBILE':
        desc = <Tag color="purple">手机号类型</Tag>;
        break;
      case 'WECHAT_MP':
        desc = <Tag color="green">微信公众号</Tag>;
        break;
      case 'WECHAT_MINIAPP':
        desc = <Tag color="green">微信小程序</Tag>;
        break;
      case 'WECHAT_OPEN':
        desc = <Tag color="green">微信PC</Tag>;
        break;
      default:
        break;
    }

    return desc;
  };

  const auths = bizData?.auths || [];

  return (
    <div className={'user-auth-list-page'}>
      <div className={'user-auth-list-wrap'}>
        <ProList<API.Auth>
          rowKey="id"
          headerTitle={null}
          loading={loading}
          showActions="always"
          split={true}
          dataSource={lodash.orderBy(auths, ['identityType'])}
          metas={{
            title: {
              render: (dom, item) => {
                return null;
              },
            },
            subTitle: {
              render: (dom, item) => {
                return (
                  <div>
                    {getIdentityTypeDesc(item.identityType)}
                    <Tag
                      color={item.verified ? '#5BD8A6' : '#c44545'}
                      style={{
                        marginRight: 8,
                      }}
                    >
                      {item.verified ? '已验证' : '未验证'}
                    </Tag>
                  </div>
                );
              },
            },
            actions: {
              render: (dom, item) => {
                let itemActions: any = [];
                if (item.identityType.startsWith('PWD_')) {
                  if (props.bizId) {
                    itemActions = [
                      <a
                        key={'resetpwd_action'}
                        onClick={() => {
                          KfModal.confirm(
                            `重置密码`,
                            <span>
                                                            {getIdentityTypeDesc(item.identityType)} {item.identifier}
                                                        </span>,
                            () => {
                              resetAuthPwd({authId: item.id}).then((resp) => {
                                if (resp.flag) {
                                  message.success(`重置成功, 新密码: ${resp.data}`);
                                }
                              });
                            },
                          );
                        }}
                      >
                        重置密码
                      </a>,
                    ];
                  } else {
                    itemActions = [
                      <a
                        key={'modifypwd_action'}
                        onClick={() => {
                          setModifyPwdAuth(item);
                          setModifyPwdModalVisiable(true);
                        }}
                      >
                        修改密码
                      </a>,
                    ];
                  }
                }
                return [
                  ...itemActions,
                  <a
                    key={'deletepwd_action'}
                    className={'delete-auth-action'}
                    onClick={() => {
                      KfModal.deleteConfirm(item.identifier, () => {
                        deleteUserAuth(bizData!.id!, item.id).then((resp) => {
                          if (resp.flag) {
                            message.info('删除成功');
                            loadData();
                          }
                        });
                      });
                    }}
                  >
                    删除
                  </a>,
                ];
              },
            },
            description: {
              render: (dom, item) => {
                return item.platformIdentifierName || item.identifier;
              },
            },
          }}
        />
      </div>
      <div className={'user-auth-list-tools'}>
        <Button
          type={'primary'}
          onClick={() => {
            setCreateAuthModalVisiable(true);
          }}
        >
          新增关联账号
        </Button>
      </div>

      {modifyPwdAuth && modifyPwdModalVisiable && (
        <KfModal
          title={
            <span>
                            {' '}
              <Tag color="blue">{getIdentityTypeDesc(modifyPwdAuth.identityType)}</Tag>
              {modifyPwdAuth.identifier} - 密码修改
                        </span>
          }
          width={480}
          open={modifyPwdModalVisiable}
          onCancel={() => {
            setModifyPwdModalVisiable(false);
            setModifyPwdAuth(null);
          }}
          onSubmitted={() => {
            return true;
          }}
        >
          <ModifyPasswordForm/>
        </KfModal>
      )}

      {bizData && createAuthModalVisiable && (
        <KfModal
          title={`新增关联账号`}
          width={480}
          open={createAuthModalVisiable}
          onCancel={() => {
            setCreateAuthModalVisiable(false);
          }}
          onSubmitted={() => {
            loadData();
          }}
        >
          <CreateAuthForm userId={bizData.id!}/>
        </KfModal>
      )}
    </div>
  );
};

export default AuthList;
